﻿using System;
using System.Drawing;
using System.Windows.Forms;
using InformationSystem.Entity;
using InformationSystem.Service;

namespace InformationSystem
{
	/// <summary>
	/// Description of AddStudent.
	/// </summary>
	public partial class AddStudent : Form
	{
		UserService userService;
		
		User user = null;
		
		public AddStudent(UserService _userService)
		{			
			InitializeComponent();	

			userService = _userService;
			
			this.Text = "Add Student";
			
		}
		
		
		public AddStudent(UserService _userService, int _userId)
		{			
			InitializeComponent();	

			userService = _userService;
			
			this.Text = "Modify Student";
			
			
			user = new User();
			user.id = _userId;
			
			user = userService.query(user);
			
			tbName.Text = user.name;
			tbAge.Text = user.age.ToString();
			tbPhone.Text = user.phone;
			tbAddress.Text = user.address;
			
		}
		
		void BtSaveClick(object sender, EventArgs e)
		{
			if(tbName.Text == "")
			{
				MessageBox.Show("Please input name");
				return;
			}
			
			if(tbAge.Text == "")
			{
				MessageBox.Show("Please input age");
				return;
			}
			
			int age = 0;
			
			if(!Int32.TryParse(tbAge.Text,out age))
			{
				MessageBox.Show("Age must be a number");
				return;
			}
			
			
			if(tbPhone.Text == "")
			{
				MessageBox.Show("Please input phone");
				return;
			}
			
			if(tbAddress.Text == "")
			{
				MessageBox.Show("Please input address");
				return;
			}
			
			if(user == null)
			{
				user = new User();
			}
			user.name = tbName.Text;
			user.age = age;
			user.phone = tbPhone.Text;
			user.address = tbAddress.Text;
			
			if(userService.addOrUpdate(user))
			{
				MessageBox.Show("save successful");
			}
			else
			{
				MessageBox.Show("save failed");
			}
			
		}
		void BtCloseClick(object sender, EventArgs e)
		{
			this.Close();
		}
	}
}
